<?php

namespace apiend\modules\test\controllers;

use Yii;
use apiend\components\Controller;

/**
 * RsaController for the `test` module
 */
class RsaController extends Controller {

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex() {

        //原始数据内容
        $data = 'wO8fSKeyjm6H2AAgLQs7i3WuxapFl35_';
        $security = Yii::$app->security;
        $encrypt_data = $security->encryptDataByKey($data);
        $decrypt_data = $security->decryptDataByKey($encrypt_data);

        $test = 'MStYUGFpNkxRVVVZdHJNY2lvS29ncUE9PQ==';
        $test_decrypt_data = $security->decryptDataByKey($test);

        return [
            'data' => $data,
            'encrypt_data' => $encrypt_data,
            'decrypt_data' => $decrypt_data,
            'test' => $test,
            'test_decrypt_data' => $test_decrypt_data,
        ];
    }

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndexOld() {

        //得到32位固定密钥
        $key = md5('key');
        //原始数据内容
        $data = '123456';

        //1、生成0-32之间的随机数字 ==> $pos
        $pos = rand(0, 32);

        //2、拼接key字符串成64位字符串（key+key）==>> $newkey
        $newkey = $key . $key;

        //3、iv为16位字符串，通过 第二步拼接的$newkey 截取 pos开始位置 的 16位字符
        $iv = substr($newkey, $pos, 16);

        //4、将pos作为ascii码转成字母（或符号） ==>> prefix
        $prefix = chr($pos + 48);

        //5、openssl_encrypt加密 OPENSSL_RAW_DATA的值是1, 为 ==>> $enstring
        $enstring = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);

        //6、拼接 $prefix + $enstring 成新的加密内容串然后base64encode 返回 $encrypt_data
        $encrypt_data = base64_encode($prefix . base64_encode($enstring));


        //base64_decode密文openssl_decrypt解密后的数据
        $edata = base64_decode($encrypt_data);
        $pos = ord(substr($edata, 0, 1)) - 48;

        $iv = substr($key . $key, $pos, 16);

        $decrypt_data = openssl_decrypt(substr($edata, 1), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);

        return [
            'key' => $key,
            'pos' => $pos,
            'pos_hex' => chr($pos + 48),
            'data' => $data,
            'iv' => $iv,
            'encrypt_data' => $encrypt_data,
            'decrypt_data' => $decrypt_data,
        ];
    }

}
